﻿using System.IO;
using Microsoft.Xna.Framework.Graphics;

namespace Ultima.Xna.Data
{
    public class Gumps
    {
        private static FileIndex _fileIndex = new FileIndex("Gumpidx.mul", "Gumpart.mul", 0x10000, 12);
        public static FileIndex FileIndex { get { return _fileIndex; } }

        public unsafe static Texture2D CreateTexture(GraphicsDevice graphicsDevice, int index)
        {
            int length, extra;
            bool patched;
            Stream stream = _fileIndex.Seek(index, out length, out extra, out patched);

            if (stream == null)
                return null;

            int width = (extra >> 16) & 0xFFFF;
            int height = extra & 0xFFFF;

            uint[] pixels = new uint[width * height];
            BinaryReader bin = new BinaryReader(stream);

            int[] lookups = new int[height];
            int start = (int)bin.BaseStream.Position;

            for (int i = 0; i < height; ++i)
                lookups[i] = start + (bin.ReadInt32() * 4);

            fixed (uint* line = &pixels[0])
            {
                for (int y = 0; y < height; ++y)
                {
                    bin.BaseStream.Seek(lookups[y], SeekOrigin.Begin);

                    uint* cur = line + (y * width);
                    uint* end = cur + (width);

                    while (cur < end)
                    {
                        uint color = bin.ReadUInt16();
                        uint* next = cur + bin.ReadUInt16();

                        if (color == 0)
                        {
                            cur = next;
                        }
                        else
                        {
                            uint color32 = 0xff000000 + (
                                ((((color >> 10) & 0x1F) * 0xFF / 0x1F) << 16) |
                                ((((color >> 5) & 0x1F) * 0xFF / 0x1F) << 8) |
                                (((color & 0x1F) * 0xFF / 0x1F))
                                );
                            while (cur < next)
                                *cur++ = color32;
                        }
                    }
                }
            }

            Texture2D texture = new Texture2D(graphicsDevice, width, height);
            texture.SetData(pixels);

            return texture;
        }
    }
}